import atexit
import sys
import os
import importlib.abc
import importlib.util
import time

my_code_temp = []


class ImageImporter(importlib.abc.MetaPathFinder, importlib.abc.Loader):
    def __init__(self):
        self.image_extensions = ['.png', '.jpg', '.jpeg']

    def find_spec(self, fullname, path, target=None):
        # 将模块名转换为可能的图片文件名
        parts = fullname.split('.')
        module_name = parts[-1]

        # 如果是包内导入，path是包的__path__列表
        if path:
            base_path = path[0]
        else:
            base_path = os.getcwd()

        # 尝试在包目录下查找图片
        for ext in self.image_extensions:
            image_path = os.path.join(base_path, f"{module_name}{ext}")
            if os.path.exists(image_path):
                with open(image_path, 'rb') as f:
                    content = f.read()

                if self._has_hidden_code(content):
                    return importlib.util.spec_from_loader(
                        fullname,
                        self,
                        origin=image_path
                    )

        return None

    def _has_hidden_code(self, content):
        markers = [b'###CODE_START###', b'#PYTHON_CODE#', b'BEGIN_PYTHON']
        return any(marker in content for marker in markers)

    def _parse_config(self, code):
        """解析获取配置信息"""

        quotation = code[0]  # 引号使用的类型
        re_code = (quotation * 3) + "hide-code-config(.*?)" + ("quotation" * 3)


    def create_module(self, spec):
        return None  # 使用默认模块创建

    def exec_module(self, module):
        with open(module.__spec__.origin, 'rb') as f:
            content = f.read()

        code: str = self._extract_code(content)

        has_config = code.startswith('"""hide-code-config') or code.startswith("'''hide-code-config")  # 是否存在配置
        if has_config:
            self._parse_config(code)

        try:
            exec(code, module.__dict__)
        except Exception as e:
            py_filename = ""
            if module.__spec__.origin.endswith('.png'):
                # 替换最后.png为.py
                py_filename = module.__spec__.origin[:-4] + '.py'
            else:
                raise ImportError(f"代码执行报错:{e}, 你可以使用png图片实现转化为代码到本地的功能")
            with open(py_filename, 'w') as f:
                f.write(code)

            my_code_temp.append(py_filename)

    def _extract_code(self, content):
        separator = b'###CODE_START###'
        if separator in content:
            return content.split(separator)[1].decode('utf-8')

        if content.endswith(b'\xFF\xD9'):  # JPEG
            eof_pos = content.rfind(b'\xFF\xD9') + 2
        elif b'IEND' in content:  # PNG
            iend_pos = content.rfind(b'IEND')
            eof_pos = iend_pos + 8
        else:
            eof_pos = max(0, len(content) - 1024)

        return content[eof_pos:].decode('utf-8', errors='ignore')


# 注册导入钩子
sys.meta_path.insert(0, ImageImporter())


def remove_temp():
    for filename in my_code_temp:
        os.remove(filename)
        print(f"finished remove temp-file:{os.path.basename(filename)}")


atexit.register(remove_temp)
